package com.macaku.controller;

import cn.hutool.core.bean.BeanUtil;
import com.macaku.config.AppConfig;
import com.macaku.domain.dto.EMailDTO;
import com.macaku.domain.dto.ModelMessage;
import com.macaku.domain.po.Email;
import com.macaku.service.EmailService;
import com.macaku.utils.MediaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apiguardian.api.API;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2024-01-14
 * Time: 19:10
 */
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/email")
@Api(tags = "邮箱相关接口")
public class EmailController {

    private final EmailService emailService;

    @PostMapping("/send")
    @ApiOperation("发送普通消息")
    public void sendEmail(EMailDTO eMailDTO) {
        Email email = BeanUtil.copyProperties(eMailDTO, Email.class);
        email.setCreateTime(new Date());
        emailService.sendSimpleMailMessage(email);
        log.info("发送成功");
    }

    @PostMapping("/attachment")
    @ApiOperation("发送带附件消息")
    public void sendEmailWithAttachment(EMailDTO eMailDTO,
                                        @ApiParam("附件") @NonNull @RequestPart("attachment") MultipartFile file) {
        // 获得一个唯一的路径
        String uniquePath = MediaUtils.getImageUniquePath(file.getOriginalFilename());
        // 加载
        String path = AppConfig.ROOT + uniquePath;
        File attachment = MediaUtils.loadFile(file, path);
        // 发送邮件
        Email email = BeanUtil.copyProperties(eMailDTO, Email.class);
        email.setCreateTime(new Date());
        emailService.sendMailWithFile(email, attachment);
//        attachment.delete();//删除附件在本地的保存
        log.info("发送成功");
    }

    @PostMapping("/model")
    @ApiOperation("发送模板消息")
    public void sendModelMail(EMailDTO eMailDTO) {
        Email email = BeanUtil.copyProperties(eMailDTO, Email.class);
        email.setCreateTime(new Date());
        // 构造模板消息
        ModelMessage modelMessage = new ModelMessage();
        modelMessage.setTitle(email.getTitle());
        modelMessage.setContent(email.getContent());
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(email.getCreateTime());
        modelMessage.setCreateTime(date);
        modelMessage.setSenderName(emailService.selectNameByEmail(email.getSender()));
        modelMessage.setRecipientName(emailService.selectNameByEmail(email.getRecipient()));
        // 发送模板消息
        emailService.sendModelMail(email, modelMessage);
//        attachment.delete();//删除附件在本地的保存
        log.info("发送成功");
    }



}
